import React, { useState, useEffect } from 'react';
import {
  WifiOutlined,
  ClockCircleOutlined,
  UserOutlined,
  HomeOutlined,
  BellOutlined,
  SettingOutlined,
  LogoutOutlined,
  PhoneOutlined,
  WechatOutlined,
  CustomerServiceOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { Avatar, Badge, Dropdown, Space, Tooltip, Modal } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import './Header.css';
import { setMerchantId } from '../../services';

interface MerchantInfo {
  id: number;
  name: string;
  status: number;
  apiKey: string;
  createdAt: string;
  updatedAt: string;
}

export const GlobalHeader: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [currentTime, setCurrentTime] = useState(new Date());
  const [wifiStrength, setWifiStrength] = useState(4); // 1-4 表示信号强度
  const [contactModalVisible, setContactModalVisible] = useState(false);
  const [merchantInfo, setMerchantInfo] = useState<MerchantInfo | null>(null);
  const [batteryLevel, setBatteryLevel] = useState<number>(92);

  // 判断是否处于首页
  const isDashboard = location.pathname === '/dashboard';

  // 更新时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 获取商户信息
  const getMerchantInfo = async () => {
    try {
      const response = await fetch('/admin/merchant', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      const result = await response.json();
      if (result.code === 0) {
        setMerchantInfo(result.data);
        setMerchantId(result.data.id);
      }
    } catch (error) {
      console.error('获取商户信息失败:', error);
    }
  };

  // 获取电池电量
  const getBatteryLevel = async () => {
    try {
      if ('getBattery' in navigator) {
        // @ts-expect-error Battery API is not included in standard Navigator type definitions
        const battery = await navigator.getBattery();
        setBatteryLevel(Math.round(battery.level * 100));

        // 监听电量变化
        battery.addEventListener('levelchange', () => {
          setBatteryLevel(Math.round(battery.level * 100));
        });
      }
    } catch (error) {
      console.warn('无法获取电池信息:', error);
    }
  };

  // 初始化数据
  useEffect(() => {
    getMerchantInfo();
    getBatteryLevel();
  }, []);

  // 格式化时间
  const formatTime = () => {
    return currentTime.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  };

  // 模拟随机Wi-Fi信号强度
  useEffect(() => {
    const signalTimer = setInterval(() => {
      const randomStrength = Math.max(1, Math.floor(Math.random() * 5));
      setWifiStrength(randomStrength);
    }, 30000); // 每30秒更新一次

    return () => clearInterval(signalTimer);
  }, []);

  // 渲染Wi-Fi信号强度图标
  const renderWifiIcon = () => {
    return (
      <div className="wifi-icon">
        <WifiOutlined />
        <span className="signal-strength">{wifiStrength}</span>
      </div>
    );
  };

  // 处理登出
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    navigate('/login');
  };

  // 用户菜单项
  const userMenuItems = [
    {
      key: 'profile',
      label: '个人资料',
      icon: <UserOutlined />,
      onClick: () => navigate('/profile'),
    },
    {
      key: 'settings',
      label: '账户设置',
      icon: <SettingOutlined />,
      onClick: () => navigate('/settings'),
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  return (
    <>
      <header className={`global-header ${isDashboard ? 'dashboard-header' : ''}`}>
        <div className="header-left">
          <div className="header-logo" onClick={() => navigate('/dashboard')}>
            <img src="/beria.png" alt="logo" className="header-logo-icon" />
            <span className="logo-text">
              贝利亚精酿啤酒餐饮系统
            </span>
          </div>

          <div className="header-system-info">
            <div className="time">
              <ClockCircleOutlined />
              <span>{formatTime()}</span>
            </div>
            {renderWifiIcon()}
          </div>
        </div>

        <div className="header-right">
          <h1 style={{ textTransform: 'uppercase', fontSize: 20 }}>{merchantInfo?.name}</h1>

          <div className="contact-info">
            <Tooltip title="联系我们">
              <CustomerServiceOutlined
                className="contact-item"
                onClick={() => setContactModalVisible(true)}
              />
            </Tooltip>
          </div>

          <Space size={12}>
            <div className="battery">
              <ThunderboltOutlined style={{ fontSize: '18px' }} />
              <span>{batteryLevel}%</span>
            </div>
          </Space>

          <div className="header-actions">
            <Badge count={5} className="notification-badge">
              <BellOutlined style={{ fontSize: '18px' }} />
            </Badge>

            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <div className="user-info">
                <Avatar size="small" icon={<UserOutlined />} />
                <span className="user-name">管理员</span>
              </div>
            </Dropdown>
          </div>
        </div>
      </header>

      {/* 联系方式弹窗 */}
      <Modal
        title="联系我们"
        open={contactModalVisible}
        onCancel={() => setContactModalVisible(false)}
        footer={null}
        width={400}
      >
        <div className="contact-modal-content">
          <div className="contact-modal-item">
            <WechatOutlined className="contact-modal-icon" />
            <div className="contact-modal-info">
              <div className="contact-modal-label">微信</div>
              <div className="contact-modal-value">liuyishun001</div>
            </div>
          </div>
          <div className="contact-modal-item">
            <PhoneOutlined className="contact-modal-icon" />
            <div className="contact-modal-info">
              <div className="contact-modal-label">电话</div>
              <div className="contact-modal-value">13727521102</div>
            </div>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default GlobalHeader; 